<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :showBefore="true">
        <span slot="before">共{{ total }}条记录</span>
        <template v-slot:after>
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import?tupe=user')"
            >导入</el-button
          >
          <el-button size="small" type="danger" @click="exportData"
            >导出</el-button
          >
          <el-button size="small" type="primary" @click="isDialog = true"
            >新增员工</el-button
          >
        </template>
      </PageTools>

      <!-- 表格 -->
      <el-card>
        <el-table border :data="data">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" align="center">
            <template slot-scope="{ row }">
              <img
                slot="reference"
                ref="liu"
                @click="showDialog(row.staffPhoto)"
                v-imagerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="
                  border-radius: 50%;
                  width: 100px;
                  height: 100px;
                  padding: 10px;
                "
                alt=""
              />
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="手机号" sortable="" prop="mobile" />
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatterEmployment"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template v-slot="{ row }">
              <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="$router.push('/detail/' + row.id)"
                >查看</el-button
              >
              <!-- <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button> -->
              <el-button type="success" size="small" @click="juese(row.id)"
                >角色</el-button
              >
              <el-button type="danger" size="small" @click="delYuan(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-size="pageSize"
          >
          </el-pagination>
        </el-row>
        <!-- 、分页组件 -->
      </el-card>
      <!-- 、表格 -->
    </div>

    <!-- 添加员工 -->
    <AddEmployee :isDialog.sync="isDialog" />
    <!-- 、添加员工 -->

    <!-- 二维码弹出 -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="250px">
      <canvas ref="liu"></canvas>
    </el-dialog>
    <!-- /二维码弹出 -->

    <!-- 修改角色权限 -->
    <AssginRole
      ref="juese"
      :isShowRole.sync="isShowRole"
      :userId="userId"
    ></AssginRole>
    <!-- /修改角色权限 -->
  </div>
</template>

<script>
import { getEmployeeList, delEmployeed } from "@/api/employees";
import EmployeeEnum from "@/api/constant/employees.js";
import AddEmployee from "./components/add-employee.vue";
import { formatDate } from "@/filters/";
import QrCode from "qrcode";
import AssginRole from "./components/assign-role.vue";
export default {
  created() {
    this.getList();
  },
  components: {
    AddEmployee,
    AssginRole,
  },
  data() {
    return {
      data: [],
      pageSize: 8, // 当前个数
      total: 0,
      pageNum: 1, // 当前页码
      isDialog: false, // 添加员工显示
      dialogVisible: false, // 头像二维码显示隐藏
      isShowRole: false, // 角色授权对话框
      userId: null, // 点击角色保存的id
    };
  },
  methods: {
    async getList() {
      const data = await getEmployeeList({
        page: this.pageNum,
        size: this.pageSize,
      });
      this.data = data.rows;
      this.total = data.total;
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getList();
    },
    // 格式化 聘用形式
    formatterEmployment(row, column, cellValue, index) {
      cellValue;
      let str = EmployeeEnum.hireType.find((item) => item.id === cellValue);
      return str ? str.value : "未知";
    },
    // 删除员工
    async delYuan(id) {
      try {
        await this.$confirm("此操作将永久删除该员工, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        await delEmployeed(id);
        this.$message({
          message: "删除成功",
          type: "success",
        });
        this.getList();
      } catch (error) {
        this.$message({
          type: "info",
          message: "已取消删除",
        });
      }
    },
    // 导出表格成 Excel 数据
    exportData() {
      import("@/vendor/Export2Excel").then(async (excel) => {
        // 一次 获取员工的所有数据 有多少获取多少
        const { rows } = await getEmployeeList({
          page: 1,
          size: this.total,
        });
        const headers = {
          姓名: "username",
          手机号: "mobile",
          入职日期: "timeOfEntry",
          聘用形式: "formOfEmployment",
          转正日期: "correctionTime",
          工号: "workNumber",
          部门: "departmentName",
        };
        let data = this.formatJson(headers, rows);
        // console.log(data);
        const multiHeader = [["姓名", "主要信息", "", "", "", "", "部门"]]; // 给表格在添加一个头
        const merges = ["A1:A2", "B1:F1", "G1:G2"];
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          multiHeader,
          merges,
          autoWidth: true,
          filename: "员工资料表",
        });
      });
    },
    // 处理数据变成 可导入成 Excel 的文件
    formatJson(headers, rows) {
      return rows.map((item) => {
        return Object.values(headers).map((item2) => {
          if (item2 === "correctionTime" || item2 === "timeOfEntry") {
            return formatDate(item[item2]);
          } else if (item2 === "formOfEmployment") {
            var en = EmployeeEnum.hireType.find((p) => p.id === item[item2]);
            return en ? en.value : "未知 ";
          }
          return item[item2];
        });
      });
    },
    showDialog(url) {
      if (url) {
        this.dialogVisible = true;
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.liu, url);
        });
      } else {
        this.$message("默认图片不能生成二维码");
      }
    },
    // 点击角色
    async juese(id) {
      await this.$refs.juese.getList(id);
      this.userId = id;
      this.isShowRole = true;
    },
  },
};
</script>

<style>
</style>
